//
//  PhotosViewController.m
//  MPFindPart
//
//  Created by xalo on 16/5/2.
//  Copyright © 2016年 马鹏. All rights reserved.
//

#import "PhotosViewController.h"
#import "PhotoCell.h"
#import "DetailPhotoController.h"
#import "UICollectionView+EmptyData.h"
#import "LHFileReadAndWriteTools.h"

@interface PhotosViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UICollectionView *collection;

@property (strong,nonatomic)NSString *fileStr;//记录存储路径的方法
@property (strong,nonatomic)NSMutableArray *localImageArray;//存储本地的图片数组

@property (assign,nonatomic)float cellHeight;//每个item的高度，item的高度和宽度大小相等

@property (strong,nonatomic)NSIndexPath *indexPath;//记录下标


@end

@implementation PhotosViewController

#pragma mark  视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"私密相册";
    self.automaticallyAdjustsScrollViewInsets = NO;
    //打开self.view的用户交互
    self.view.userInteractionEnabled = YES;
    self.collection.backgroundColor = [UIColor whiteColor];
    //添加右侧按钮，管理相册
    [self addRightBarButtonItem];
    
    //注册xib
    [self.collection registerNib:[UINib nibWithNibName:@"PhotoCell" bundle:nil] forCellWithReuseIdentifier:@"PhotoCell"];

}
- (void)viewWillAppear:(BOOL)animated{
    
    //从云端读取数据
    [self readImageFromCloud];
}

#pragma mark   从云端读取照片
- (void)readImageFromCloud{
    
    //将数组滞空
    self.localImageArray = nil;
    //获取用户的粉丝和关注
    [[AVUser currentUser] getFollowersAndFollowees:^(NSDictionary *dict, NSError *error) {
        
        NSMutableArray *followers = [NSMutableArray array];
        if ([dict[@"followers"] count]) {
            
            [followers addObject:dict[@"followers"]];
        }
        else if ([dict[@"followees"] count]) {
            
            [followers addObject:dict[@"followees"]];
        }
        NSMutableArray *array = followers.firstObject;
        //在Photo表中查询图片
        AVQuery *query = [AVQuery queryWithClassName:@"Photo"];
        //字符串查询 查询对方的图片信息
        [query whereKey:@"userName" hasPrefix:array.firstObject[@"username"]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            NSLog(@"%@",objects);
            
            for (AVObject *object in objects) {
                
                if ([object[@"userName"] isEqualToString:array.firstObject[@"username"]]) {
                    
                    NSLog(@"PhotoImage = %@",[object objectForKey:@"PhotoImage"]);
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:object[@"PhotoImage"],@"imageStr",object[@"objectId"],@"objectId", nil];
                    [self.localImageArray addObject:dic];
                    
                }
            }
            [self.collection reloadData];
        }];
    }];
    AVQuery *query = [AVQuery queryWithClassName:@"Photo"];
    //字符串查询   查询当前用户的图片信息
    [query whereKey:@"userName" hasPrefix:[AVUser currentUser].username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        for (AVObject *object in objects) {
            
            if ([object[@"userName"] isEqualToString:[AVUser currentUser].username]) {
                
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:object[@"PhotoImage"],@"imageStr",object[@"objectId"],@"objectId", nil];
                [self.localImageArray addObject:dic];
            }
        }
        [self.collection reloadData];
    }];
}
#pragma mark --------collectionView的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return [collectionView showMessage:@"相册还是空的，快来上传幸福的瞬间吧" byDataArrayCount:self.localImageArray.count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    self.indexPath = indexPath;
    PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCell" forIndexPath:indexPath];

    NSDictionary *dic = self.localImageArray[indexPath.row];
    NSURL *imageStr = dic[@"imageStr"];
    [cell.PhotoImageView sd_setImageWithURL:imageStr];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongAction:)];
    [cell addGestureRecognizer:longPress];
    return cell;
}

#pragma mark  删除图片（手势的回调方法）
- (void)LongAction:(UILongPressGestureRecognizer *)sender{
    
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"删除图片" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        //删除图片的操作
        UICollectionViewCell *cell = (UICollectionViewCell *)sender.view;
        NSIndexPath *indexPath = [self.collection indexPathForCell:cell];
        
        if (self.localImageArray.count > 1) {
            
            [AVQuery doCloudQueryInBackgroundWithCQL:[NSString stringWithFormat:@"delete from Photo where objectId='%@'",[self.localImageArray objectAtIndex:indexPath.row][@"objectId"]] callback:^(AVCloudQueryResult *result, NSError *error) {
                
                [self.localImageArray removeObjectAtIndex:indexPath.row];
                [self.collection deleteItemsAtIndexPaths:@[indexPath]];
                NSLog(@"error = %@",error);
            }];
        }
        else {
            
            [AVQuery doCloudQueryInBackgroundWithCQL:[NSString stringWithFormat:@"delete from Photo where objectId='%@'",[self.localImageArray objectAtIndex:indexPath.row][@"objectId"]] callback:^(AVCloudQueryResult *result, NSError *error) {
                
                [self.localImageArray  removeAllObjects];
                [self.collection reloadData];
            }];
        }
        
    }];
    [alertController addAction:sureAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];

}
//点击每个item的时候执行的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
        self.hidesBottomBarWhenPushed = YES;
        DetailPhotoController *detailVC = [[DetailPhotoController alloc] init];
        detailVC.receiveImageArray = self.localImageArray;
        detailVC.indexPath = indexPath;
        [self.navigationController pushViewController:detailVC animated:YES];
        self.hidesBottomBarWhenPushed = NO;
}

//返回每个item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    self.cellHeight = (kWidth - 50)/3;
    return CGSizeMake(self.cellHeight, self.cellHeight);
}
//item上下左右的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
//添加右侧按钮对相册进行管理
- (void)addRightBarButtonItem{
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"管理" style:UIBarButtonItemStylePlain target:self action:@selector(managedPhoto:)];
    
}
//右侧按钮的回调方法
- (void)managedPhoto:(UIBarButtonItem *)sender{
    
    UIAlertController *alertController = [UIAlertController  alertControllerWithTitle:@"管理相册" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"删除所有" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您将删除所有的图片" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
           
            //执行删除图片的操作
            [self.localImageArray removeAllObjects];
            [self writeToWithMemory:self.localImageArray];
            [self.collection reloadData];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [controller addAction:sureAction];
        [controller addAction:cancelAction];
        [self presentViewController:controller animated:YES completion:nil];
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"上传图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        
        UIAlertAction *fromCameraAction = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //从相册中选取图片
            [self createImagePicker];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [controller addAction:fromCameraAction];
        
        [controller addAction:cancelAction];
        
        [self presentViewController:controller animated:YES completion:nil];
        
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    
    [alertController addAction:action];
    [alertController addAction:deleteAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}


//调用系统相册
- (void)createImagePicker{
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = YES;
    picker.delegate = self;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark imagePickerController的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    NSString *imageStr = [self makeImageToString:imageView.image];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:imageStr,@"imageStr", nil];
    self.localImageArray = [self readArray];
    [self.localImageArray addObject:dic];
    [self writeToWithMemory:self.localImageArray];
    
    AVObject *object = [AVObject objectWithClassName:@"Photo"];
    [object setObject:[AVUser currentUser].username forKey:@"userName"];
    
    AVFile *file = [AVFile fileWithName:@"image.png" data:UIImageJPEGRepresentation(imageView.image, 2.0)];
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
       
        if (succeeded) {
            
            NSLog(@"---fileUrl = %@",file.url);
            [object setObject:file.url forKey:@"PhotoImage"];
            //暂缓保存图片
            [object saveEventually:^(BOOL succeeded, NSError *error) {
               
                if (succeeded) {
                    
                    NSLog(@"文件保存成功");
                    
                }else{
                    
                    NSLog(@"文件保存失败-%@",error);
                }
            }];
            
        }else{
            
            NSLog(@"----==%@",error);
        }
    }];
    dispatch_async(dispatch_get_main_queue(), ^{
       
         [self.collection reloadData];
    });
   
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//UIImage转换为NSString

-(NSString *)makeImageToString:(UIImage *)image{
    //第一步，先将image转换为data类型
    NSData *imageData = UIImageJPEGRepresentation(image, 2.0);
    //将NSData类型转换为NSString类型
    NSString *string = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return string;
}

//NSString转换为UIImage

-(UIImage *)makeStringToImage:(NSString *)string{
    //将字符串转换为data类型
    NSData *strData = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    //将data转换为图片
    UIImage *image = [UIImage imageWithData:strData];
    return image;
}

//数组写入
- (void)writeToWithMemory:(NSMutableArray *)array {
    
    NSString *path = [[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"Photo.plist"];
    BOOL isWrite = [array writeToFile:path atomically:YES];
    if (!isWrite) {
        
        [self showAlertViewWithMessage:@"保存失败啦!快检查一下你的网络..."];
    }
}

//数组读取
- (NSMutableArray *)readArray {
    
    NSString *path = [[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"Photo.plist"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
    return array;
}
//弹出警示框的方法
- (void)showAlertViewWithMessage:(NSString *)message{
    
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
        
       
}

#pragma mark ----------属性懒加载

- (NSMutableArray *)localImageArray{
    
    if (!_localImageArray) {
        
        _localImageArray = [NSMutableArray array];
    }
    return _localImageArray;
}
- (NSString *)fileStr{
    
    if (!_fileStr) {
        
        _fileStr = [[NSString alloc] init];
    }
    return _fileStr;
}
-(NSIndexPath *)indexPath{
    
    if (!_indexPath) {
        
        _indexPath = [[NSIndexPath alloc] init];
    }
    return _indexPath;
}


@end
